package org.openkoala.security.application.impl;

import java.util.List;
import java.util.Set;

import javax.inject.Named;

import org.dayatang.domain.EntityRepository;
import org.dayatang.domain.InstanceFactory;
import org.dayatang.querychannel.JdbcTemplateObj;
import org.openkoala.security.application.SecurityAccessApplication;
import org.openkoala.security.core.domain.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

@Named
@Transactional
public class SecurityAccessApplicationImpl implements SecurityAccessApplication {
	@Autowired
	private JdbcTemplateObj jdbcTemplateObj;

	public List<Role> findAllRolesByUserAccount(String userAccount) {
		return User.findAllRolesBy(userAccount);
	}

	public User getUserById(Long userId) {
		return Actor.get(User.class, userId);
	}

	@Override
	public <T extends Actor> T getActorById(Long actorId) {
		return Actor.getActorBy(actorId);
	}

	public User getUserByUserAccount(String userAccount) {
		return User.getByUserAccount(userAccount);
	}

	public List<MenuResource> findMenuResourceByUserAccount(String userAccount) {
		return Authority
				.findMenuResourceByAuthorities(Authorization.findAuthoritiesByActor(getUserByUserAccount(userAccount)));
	}

	@Override
	public boolean updatePassword(User user, String userPassword, String oldUserPassword) {
		return user.updatePassword(userPassword, oldUserPassword);
	}

	@Override
	public Role getRoleBy(Long roleId) {
		return Role.get(Role.class, roleId);
	}

	@Override
	public Permission getPermissionBy(Long permissionId) {
		return Permission.get(Permission.class, permissionId);
	}

	@Override
	public MenuResource getMenuResourceBy(Long menuResourceId) {
		return MenuResource.get(MenuResource.class, menuResourceId);
	}

	@Override
	public List<MenuResource> findAllMenuResourcesByRole(Role role) {
		return role.findMenuResourceByAuthority();
	}

	@Override
	public UrlAccessResource getUrlAccessResourceBy(Long urlAccessResourceId) {
		return UrlAccessResource.getBy(urlAccessResourceId);
	}

	@Override
	public PageElementResource getPageElementResourceBy(Long pageElementResourceId) {
		return PageElementResource.getBy(pageElementResourceId);
	}

	@Override
	public Role getRoleBy(String roleName) {
		return Role.getRoleBy(roleName);
	}

	@Override
	public <T extends Scope> T getScope(Long scopeId) {
		return Scope.getBy(scopeId);
	}

	@Override
	public boolean hasPageElementResource(String identifier) {
		return PageElementResource.hasIdentifier(identifier);
	}

	@Override
	public User getUserByEmail(String email) {
		return User.getByEmail(email);
	}

	@Override
	public User getUserByTelePhone(String telePhone) {
		return User.getByTelePhone(telePhone);
	}

	@Override
	public List<MenuResource> findAllMenuResourcesByIds(Long[] menuResourceIds) {
		return MenuResource.findAllByIds(menuResourceIds);
	}

	@Override
	public boolean checkRoleByName(String roleName) {
		return Role.checkName(roleName);
	}

	@Override
	public <T extends Authority> T getAuthority(Long authorityId) {
		return Authority.getBy(authorityId);
	}

	@Override
	public List<Role> findRolesOfUser(User user) {
		return user.findAllRoles();
	}

	@Override
	public List<Permission> findPermissionsOfUser(User user) {
		return user.findAllPermissions();
	}

	@Override
	public List<MenuResource> findMenuResourcesOfRole(Role role) {
		return role.findMenuResources();
	}

	@Override
	public List<UrlAccessResource> findUrlAccessResourcesOfRole(Role role) {
		return role.findUrlAccessResources();
	}

	@Override
	public List<PageElementResource> findPageElementResourcesOfRole(Role role) {
		return role.findPageElementResources();
	}

	@Override
	public List<SecurityResource> findResourcesByPermission(Permission permission) {
		return permission.findResources();
	}

	@Override
	public boolean hasUserExisted() {
		return User.hasUserExisted();
	}

	private EntityRepository getRepository() {
		EntityRepository repository = null;
		if (repository == null) {
			repository = InstanceFactory.getInstance(EntityRepository.class, "repository");
		}
		return repository;
	}

	@Override
	public void saveHomePageSetting(String role, String page) {
		String sql = " update drgs_hosp_koala.KS_AUTHORITIES set home_page='" + page + "' where name='" + role + "'";
		getRepository().createSqlQuery(sql).executeUpdate();
	}

	/**
	 * 
	 * @Description：授权科室
	 * @Author LiuHongJun
	 * @see org.openkoala.security.application.SecurityAccessApplication#getGrantDeps(java.lang.Long,
	 *      java.lang.String)
	 */
	@Override
	public void getGrantDeps(Long userId, String deps) {
		jdbcTemplateObj.execute("update drgs_hosp_koala.ks_actors set dep_yb='" + deps
				+ "',last_modify_time=sysdate where  id='" + userId + "'");
	}

	/**
	 * 
	 * @Description：撤销科室
	 * @Author LiuHongJun
	 * @see org.openkoala.security.application.SecurityAccessApplication#getRepealGrantDeps(java.lang.Long,
	 *      java.lang.String)
	 */
	@Override
	public void getRepealGrantDeps(Long userId, String depCodes) {
		String deps = jdbcTemplateObj.queryForObject(
				"SELECT  m.dep_yb  FROM drgs_hosp_koala.ks_actors  m  WHERE m.id= '" + userId + "'", String.class);
		String newDdeps = "";
		if (deps != null) {
			String[] oldDeps = deps.split(",");
			for (String a : oldDeps) {
				if (!depCodes.contains(a)) {
					newDdeps += a + ",";
				}
			}
			if (newDdeps.lastIndexOf(",") > 0) {
				newDdeps = newDdeps.substring(0, newDdeps.lastIndexOf(",")) + "";
			}
			jdbcTemplateObj.execute("update drgs_hosp_koala.ks_actors set dep_yb='" + newDdeps
					+ "',last_modify_time=sysdate where  id='" + userId + "'");
		}
	}
/**
 * 
 *  @Description：授权病区
 *  @Author LiuHongJun  
 *  @see org.openkoala.security.application.SecurityAccessApplication#getGrantWards(java.lang.Long, java.lang.String)
 */
	@Override
	public void getGrantWards(Long userId, String ward) {
		jdbcTemplateObj.execute("update drgs_hosp_koala.ks_actors set ward_code='" + ward
				+ "',last_modify_time=sysdate where  id='" + userId + "'");
		
	}
/**
 * 
 *  @Description：撤销科室
 *  @Author LiuHongJun  
 *  @see org.openkoala.security.application.SecurityAccessApplication#getRepealGrantWards(java.lang.Long, java.lang.String)
 */
@Override
public void getRepealGrantWards(Long userId, String wards) {
	String ward = jdbcTemplateObj.queryForObject(
			"SELECT  m.ward_code  FROM drgs_hosp_koala.ks_actors  m  WHERE m.id= '" + userId + "'", String.class);
	String newWards = "";
	if (wards != null) {
		String[] oldWards = ward.split(",");
		for (String a : oldWards) {
			if (!wards.contains(a)) {
				newWards += a + ",";
			}
		}
		if (newWards.lastIndexOf(",") > 0) {
			newWards = newWards.substring(0, newWards.lastIndexOf(",")) + "";
		}
		jdbcTemplateObj.execute("update drgs_hosp_koala.ks_actors set ward_code='" + newWards
				+ "',last_modify_time=sysdate where  id='" + userId + "'");
	}
}
}
